package com.ming.attendance.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

public class DecryptUtil {
    /**
     * 解密微信加密数据，对称解密使用的算法为 AES-128-CBC，数据采用PKCS#7填充。
     *
     * @param encryptedData 加密串
     * @param sessionKey    会话密钥
     * @param iv            解密算法初始向量
     * @return 解密后的数据
     */
    public static String decryptWxData(String encryptedData, String sessionKey, String iv) {
        try {
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec spec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                System.out.println(">>>>> 微信加密数据解析结果:{} "+ result);
                return result;
            }
        } catch (Exception e) {
            System.out.println(">>>>> 微信加密数据解析失败:" + e);
        }
        return null;
    }

    /**
     * 解密微信加密数据，对称解密使用的算法为 AES-128-CBC，数据采用PKCS#7填充。
     *
     * @param encryptedData 加密串
     * @param sessionKey    会话密钥
     * @param iv            解密算法初始向量
     * @return 解密后的数据
     */
    public static String decryptWxDataOfHutool(String encryptedData, String sessionKey, String iv) {
        AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decodeBase64(sessionKey),
                Base64.decodeBase64(iv));
        byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData));
        if (null != resultByte && resultByte.length > 0) {
            // 删除解密后明文的补位字符
            int padNum = resultByte[resultByte.length - 1];
            if (padNum < 1 || padNum > 32) {
                padNum = 0;
            }
            resultByte = Arrays.copyOfRange(resultByte, 0, resultByte.length - padNum);
            String result = new String(resultByte, StandardCharsets.UTF_8);
            // System.out.println(">>>>> 微信加密数据解析结果:{}  "+ result);
            return result;
        }
        return null;
    }

}
